package org.jeecg.modules.app.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.app.order.service.AppPowerBankOrderService;
import org.jeecg.modules.app.order.vo.ProblemOrderEnt;
import org.jeecg.modules.app.util.order.OrderIncomeUtil;
import org.jeecg.modules.power.device.entity.YlDevice;
import org.jeecg.modules.power.device.entity.YlDeviceCategory;
import org.jeecg.modules.power.device.service.IYlDeviceCategoryService;
import org.jeecg.modules.power.device.service.IYlDeviceService;
import org.jeecg.modules.power.group.service.IYlGroupService;
import org.jeecg.modules.power.order.entity.YlPowerBankOrder;
import org.jeecg.modules.power.order.service.IYlPowerBankOrderService;
import org.jeecg.modules.power.order.service.IYlProblemOrderService;
import org.jeecg.modules.power.shop.entity.YlShop;
import org.jeecg.modules.power.shop.service.IYlShopService;
import org.jeecg.modules.power.statistics.entity.YlHomeShop;
import org.jeecg.modules.power.statistics.entity.YlWeaningShop;
import org.jeecg.modules.power.statistics.mapper.YlZeroShopMapper;
import org.jeecg.modules.power.statistics.service.IYlHomeShopService;
import org.jeecg.modules.power.statistics.service.IYlWeaningShopRecordService;
import org.jeecg.modules.power.statistics.service.IYlWeaningShopService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserDepart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @BelongsProject: jeecg-boot-parent  app运营端 租借订单 业务实现层
 * @BelongsPackage: org.jeecg.modules.app.order.service.impl
 * @Author: mi
 * @CreateTime: 2024-07-27 16:08
 * @Description:
 */
@Service
public class AppPowerBankOrderServiceImpl implements AppPowerBankOrderService {




    //租借订单
    @Autowired
    private IYlPowerBankOrderService ylPowerBankOrderService;

    //小组
    @Autowired
    private IYlGroupService ylGroupService;
    @Autowired
    private RedisUtil redisUtil;//redis

    @Autowired
    private IYlShopService ylShopService;//门店表

    @Autowired
    private  IYlDeviceService ylDeviceService;//设备表


    @Autowired
    private IYlDeviceCategoryService ylDeviceCategoryService;//设备类别表

    @Autowired
    private IYlProblemOrderService ylProblemOrderService;//硬件 错误订单数



    @Autowired
    private  IYlHomeShopService ylHomeShopService;//app首页门店统计表（每天晚上统计一遍）



    @Autowired
    private  YlZeroShopMapper ylZeroShopMapper;//0元店铺记录





    @Autowired
    private IYlWeaningShopRecordService ylWeaningShopRecordService;//每天撤机门店记录表

    @Autowired
    private IYlWeaningShopService ylWeaningShopService;//撤机门店统计记录表







    /**
     * APP运营端-收益页-2级页面-门店收益-门店设备收益"
     * @param user 当前登陆用户
     * @param mark 标记 （1 、小组id 2、业务员id)
     * @param userId 业务id(标记传1传小组id、标记2 传业务员id   )
     * @return
     */
    @Override
    public Result<?> getTwoShopIncomeOrder(SysUser user, Integer mark, String userId) {
        //求出上周日期
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -7);  // 获取上一周
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);  // 设置为周一
        Date monday = calendar.getTime();

        calendar.add(Calendar.DATE, 6);  // 设置为周日
        Date sunday = calendar.getTime();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String v_monday= sdf.format(monday)+" 00:00:00";//上周开始时间
        String v_sunday= sdf.format(sunday)+" 23:59:59";//上周结束时间
        Map<String, Object> map=new HashMap();


        String key= "getTwoShopIncomeOrder"+mark+userId;//缓存key
        Object object = redisUtil.get(key);
        if (object != null) {
            map=Map.class.cast(object);
            return Result.OK(map);
        }






        QueryWrapper<YlShop> queryWrapper =new QueryWrapper<YlShop>();
        if (mark==1){
            queryWrapper.eq("org_id",userId);
        }else {
            queryWrapper.eq("bd_id",userId);
        }
        queryWrapper.select("id,shop_name as shopName ,shop_bd AS shopBd ");

        List<Map<String, Object>> mapList= ylShopService.listMaps(queryWrapper);
        for (Map<String, Object> m: mapList) {
            BigDecimal zero=new BigDecimal("0.00");//自定义模拟值
            //和上周坐比较  首先 取出 上周数据   设这个周数据 做比较
            //门店收益
            //门店订单数
            Map<String, Object> lastWeekMap=   ylPowerBankOrderService.getTwoShopIncomeOrder(m.get("id").toString(),v_monday,v_sunday);//上周数据
//            System.out.println(lastWeekMap+"==lastWeekMap");
            Map<String, Object> weekMap=   ylPowerBankOrderService.getTwoShopIncomeOrder(m.get("id").toString(),v_sunday,new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));//当前周数据
//            System.out.println(weekMap+"==weekMap");
            //门店柜机数

            List<Map<String, Object>> mapValueList=new LinkedList<>();
            Map<String, Object> mapValue=new HashMap();
            String weekPrice=  weekMap.get("orderPrice").toString();//当期周收益
            String lastWeekPrice=  lastWeekMap.get("orderPrice").toString();//上周收益
            // （337-432）除以432乘以100%，正表示上升，负表示下降，即（今减去昨）除以昨乘100%
           //compareTo方法返回值有3个，分别是 -1(小于)，0（等于），1（大于），从此我们看出只需要判断返回值和0的大小即可
            String shopType="";//0 代表 无差异 1 上涨  2下降
            String percentage="";
            BigDecimal weekPriceBigDecimal=new BigDecimal(weekPrice);//当期周收益
            BigDecimal lastWeekPriceDecimal=new BigDecimal(lastWeekPrice);//上周收益

            Map<String, Object> orderIncomeUtilMap= OrderIncomeUtil.getOrderIncomeUtilMap(weekPriceBigDecimal,lastWeekPriceDecimal);

            //如果上周收益是 0  当期周 收益是0  那么
            mapValue.put("name","门店收益");//名称
            mapValue.put("orderPrice",weekPrice);//当前周收益
            mapValue.put("shopType",orderIncomeUtilMap.get("shopType"));//0 代表 无差异 1 上涨  2下降
            mapValue.put("percentage",orderIncomeUtilMap.get("percentage"));//百分比
            mapValueList.add(mapValue);

            Map<String, Object> mapValue1=new HashMap();
            String weekQuantity=  weekMap.get("quantity").toString();//当前周数量
            String lastWeekQuantity=  lastWeekMap.get("quantity").toString();//上周数量
            Map<String, Object> orderIncomeUtilMapQuantity= OrderIncomeUtil.getOrderIncomeUtilMap(new BigDecimal(weekQuantity),new BigDecimal(lastWeekQuantity));

            mapValue1.put("name","门店订单数");//名称
            mapValue1.put("orderPrice",weekQuantity);//当前周数量
            mapValue1.put("shopType",orderIncomeUtilMapQuantity.get("shopType"));//0 代表 无差异 1 上涨  2下降
            mapValue1.put("percentage",orderIncomeUtilMapQuantity.get("percentage"));//百分比
            mapValueList.add(mapValue1);

            //门店柜机数
           Integer deviceQuantity=  ylDeviceService.count(new QueryWrapper<YlDevice>().eq("device_status",3).eq("device_type",1).eq("business_id",m.get("id").toString()));


            Map<String, Object> mapValue2=new HashMap();
            mapValue2.put("name","门店柜机数");//名称
            mapValue2.put("orderPrice",deviceQuantity);//数量
            mapValue2.put("shopType","0");//0 代表 无差异 1 上涨  2下降
            mapValue2.put("percentage","0%");//百分比
            mapValueList.add(mapValue2);

            //单柜收益
            Map<String, Object> mapValue3=new HashMap();
            mapValue3.put("name","单柜收益");//名称
            mapValue3.put("orderPrice","0.00");//收益
            mapValue3.put("shopType","0");//0 代表 无差异 1 上涨  2下降
            mapValue3.put("percentage","0%");//百分比
            mapValueList.add(mapValue3);

            //单柜订单
            Map<String, Object> mapValue4=new HashMap();
            mapValue4.put("name","单柜订单");//名称
            mapValue4.put("orderPrice","0");//数量
            mapValue4.put("shopType","0");//0 代表 无差异 1 上涨  2下降
            mapValue4.put("percentage","0%");//百分比
            mapValueList.add(mapValue4);

            //单宝收益
            Map<String, Object> mapValue5=new HashMap();
            mapValue5.put("name","单宝收益");//名称
            mapValue5.put("orderPrice","0.00");//收益
            mapValue5.put("shopType","0");//0 代表 无差异 1 上涨  2下降
            mapValue5.put("percentage","0%");//百分比
            mapValueList.add(mapValue5);
            //单宝订单
            Map<String, Object> mapValue6=new HashMap();
            mapValue6.put("name","单宝订单");//名称
            mapValue6.put("orderPrice","0");//收益
            mapValue6.put("shopType","0");//0 代表 无差异 1 上涨  2下降
            mapValue6.put("percentage","0%");//百分比
            mapValueList.add(mapValue6);

            //数组 插进去
            m.put("mapValueList",mapValueList);
        }


        map.put("quantity",mapList.size());
        map.put("shopList",mapList);

        //存储缓存 redis 缓存数据 5分钟内有效
        redisUtil.set(key, map, 300);
        return Result.OK(map);
    }

    /**
     * APP运营端-硬件问题2级页面
     * @param user 当前登陆用户
     * @param shopName 店铺名称
     * @param mark  标记 （1 、小组id 2、业务员id)
     * @param userId 业务id(标记传1传小组id、标记2 传业务员id   )
     * @param type 时间类型（1今日、2昨日、3近7天、4本月）
     * @param categoryId 机柜分类id
     * @param cancellation     取消数 1 正序 2 倒序 取消率 3正序 4 倒序
     * @return
     */
    @Override
    public Result<?> getTwoProblemOrderQuantity(SysUser user, String shopName, Integer mark, String userId, Integer type, String categoryId,Integer cancellation) {
        String sId=null;
        String groupId=null;
        if (mark==1){//小组id
            groupId=userId;
        }else {
            //根据群组id 获取数据id
            sId=userId;
        }
        //getProblemOrderQuantityList
        List<ProblemOrderEnt>  problemOrderEntList= ylProblemOrderService.getProblemOrderQuantityList(sId, groupId, type, shopName, categoryId);
        for (ProblemOrderEnt  problemOrderEnt:problemOrderEntList) {
            //求出这个MAC租借订单的数量（正常订单）
            Integer orderQuantity=  ylPowerBankOrderService.getProblemOrderAndBankOrderOrderQuantity(problemOrderEnt.getMac(),type);
           //求出订单总数
            Integer o=problemOrderEnt.getQuantity()+orderQuantity;
            problemOrderEnt.setOrderQuantity(o);//订单总数
           //求出问题率
            BigDecimal w=   new   BigDecimal(problemOrderEnt.getQuantity()).divide(new   BigDecimal(o),2, BigDecimal.ROUND_HALF_UP);
            problemOrderEnt.setCancellation(w.multiply(new   BigDecimal("100")));//百分比
        }

        if (problemOrderEntList.size()>0){

            //排序 取消数
            if (cancellation==1){//正序

                List<ProblemOrderEnt>  sx=  problemOrderEntList.stream().sorted(Comparator.comparing(student ->student.getQuantity())).collect(Collectors.toList());

                return Result.OK(sx);
            }else   if (cancellation==2){//倒序
                List<ProblemOrderEnt>  jx=  problemOrderEntList.stream().sorted(Comparator.comparing(ProblemOrderEnt ::getQuantity).reversed()).collect(Collectors.toList());
                return Result.OK(jx);
            }else   if (cancellation==3){//正序  取消率
                List<ProblemOrderEnt>  sx= problemOrderEntList.stream().sorted(Comparator.comparing(student ->student.getCancellation())).collect(Collectors.toList());
                return Result.OK(sx);
            }else {
                // 2 倒序
                List<ProblemOrderEnt>  jx=   problemOrderEntList.stream().sorted(Comparator.comparing(ProblemOrderEnt ::getCancellation).reversed()).collect(Collectors.toList());
                return Result.OK(jx);
            }
        }
        return Result.OK(problemOrderEntList);
    }


    /**
     * APP运营端-首页门店-2级页面(0收益门店数据)
     * @param user 当前登陆用户
     * @param mark 标记 （1 、小组id 2、业务员id)
     * @param userId 排序 1 正序 2 倒序
     * @return
     */
    @Override
    public Result<?> getZeroShopData(SysUser user, Integer mark, String userId,Integer cancellation) {

        Date date= DateUtils.addDaysToDate(new Date(),-1);//取出昨天
        DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
        Map map=new HashMap();

        String key= "getZeroShopData"+mark+userId+cancellation;//缓存key
        Object object = redisUtil.get(key);
        if (object != null) {
            map=Map.class.cast(object);
            return Result.OK(map);
        }
        //获取更新时间
        map.put("payTime",dateFormat.format(date));
        //获取  0收益门店 现有的  如果 没有不展示 ylZeroShopMapper
        List<Map> getZeroShopMapList=new LinkedList<>();
        Integer p=0;//店铺总数
        if (mark==1){
            getZeroShopMapList=  ylZeroShopMapper.getZeroShopMapList(null, userId,cancellation);//小组
            p= ylShopService.count(new LambdaQueryWrapper<YlShop>().eq(YlShop::getOrgId,userId));
        }else {
            getZeroShopMapList=   ylZeroShopMapper.getZeroShopMapList( userId,null,cancellation);//组员
            p= ylShopService.count(new LambdaQueryWrapper<YlShop>().eq(YlShop::getBdId,userId));
        }
        map.put("shopList",getZeroShopMapList);

        Integer shopTotal= getZeroShopMapList.size();
        map.put("shopTotal",shopTotal);//店铺总数
        if (shopTotal==0){//店铺没有
            map.put("shopProportion","0.00%");//店铺 总占比11
            List<Map>mapList=new LinkedList<>();
            //自创数据
            List<String> daysList= DateUtils.getThisYearMonthDays(30);//求出时间范围
            for (String d : daysList) {
                Map dayMap=new HashMap();
                String[] s=  d.split("-");
                dayMap.put("tian",s[1]+"."+s[2]);
                dayMap.put("shopQuantity",0);
                mapList.add(dayMap);
            }
            map.put("zeroShopLineChart", mapList);//自创 数据
        }else {
            BigDecimal s=new BigDecimal(shopTotal).divide(new BigDecimal(p),2,BigDecimal.ROUND_HALF_UP);//自定义模拟
            map.put("shopProportion",s.multiply(new BigDecimal("100"))+"%");//店铺 总占比11

            //求出折线图数据  getZeroShopLineChart
            if (mark==1){
                map.put("zeroShopLineChart", ylZeroShopMapper.getZeroShopLineChart(null, userId, 30));
            }else {
                map.put("zeroShopLineChart",  ylZeroShopMapper.getZeroShopLineChart(userId, null, 30));
            }
        }
        //        存储缓存 redis 缓存数据 5分钟内有效
        redisUtil.set(key, map, 300);
        return Result.OK(map);
    }

    /**
     * APP运营端-收益页-2级页面
     * @param user 当前登陆用户
     * @param mark 标记 （1 、小组id 2、业务员id)
     * @param userId 业务id(标记传1传小组id、标记2 传业务员id   )
     * @param type 时间类型（1今日、2昨日、3本周、4本月）
     * @return
     */
    @Override
    public Result<?> getTwoIncomeOrder(SysUser user, Integer mark, String userId, Integer type,String categoryId) {
        SimpleDateFormat formats = new SimpleDateFormat("yyyy.MM.dd HH:mm");
        Map map=new HashMap();
        String key= "getTwoIncomeOrder"+mark+userId+type+categoryId;//缓存key
        Object object = redisUtil.get(key);
        if (object != null) {
            map=Map.class.cast(object);
            return Result.OK(map);
        }
        List<String> stringList=new LinkedList<>();
        List<String> shopIdStrList=new LinkedList<>();
        if (mark==1){
            stringList=ylGroupService.getGroupUserById(userId);
            //获取负责门店
            shopIdStrList=ylShopService.getShopByIdList(null,userId);
        }else {
            //根据群组id 获取数据id
            stringList.add(userId);
            //获取负责门店
            shopIdStrList=ylShopService.getShopByIdList(userId,null);
        }


        //设备仓孔数
        Integer hole=0;
        if (shopIdStrList.size()>0){
            for (String shopId:shopIdStrList) {
                Map<String, Object> stringObjectMap=  ylDeviceService.getShopIdDeviceQuantity(shopId);
                Integer fullNumber= Integer.parseInt(stringObjectMap.get("fullNumber").toString());//仓孔数
                hole=hole+fullNumber;
            }
       }
        //获取更新时间
        map.put("payTime",formats.format(new Date()));
        Map<String, Object>  dayPowerBankOrder= ylPowerBankOrderService.getAppPowerBankOrderIncome(stringList,type);//今日
        map.put("orderPrice",dayPowerBankOrder.get("orderPrice"));
        map.put("quantity",dayPowerBankOrder.get("quantity"));
        //总收益 除以 设备空数  仓口数
        if(0==Integer.parseInt(dayPowerBankOrder.get("quantity").toString())){
            map.put("singlePrice","0.00");
        }else {
            if (0==hole){
                map.put("singlePrice","0.00");
            }else {
                BigDecimal db=new BigDecimal(dayPowerBankOrder.get("orderPrice").toString()).divide(new BigDecimal(hole),2,BigDecimal.ROUND_HALF_UP);//求出单宝收益
                map.put("singlePrice",db);

            }
        }
        //门店设备收益
        QueryWrapper<YlShop> queryWrapper =new QueryWrapper<YlShop>();
        if (mark==1){
            queryWrapper.eq("org_id",userId);
        }else {
            queryWrapper.eq("bd_id",userId);
        }


        queryWrapper.select("id,shop_name as shopName ,shop_bd AS shopBd ,shop_address as shopAddress ");
        List<Map<String, Object>> mapList= ylShopService.listMaps(queryWrapper);

        List<Map<String, Object>> mapShopList= new ArrayList<>();//最终返回结果数据 店铺下面没有设备的过滤掉


        for (Map<String, Object> m: mapList) {

            QueryWrapper<YlDevice> queryWrapperDevice =new QueryWrapper<YlDevice>();
            queryWrapperDevice.eq("device_status",3);
            queryWrapperDevice.eq("device_type",1);
            queryWrapperDevice.eq("business_id",m.get("id").toString());
            if (oConvertUtils.isNotEmpty(categoryId)){
                queryWrapperDevice.eq("device_category",categoryId);
            }
            //获取 门店下的所有设备
            List<YlDevice> ylDeviceList=     ylDeviceService.list(queryWrapperDevice);
            if (ylDeviceList.size()>0){
                //组装数据
                List<Map<String, Object>> mapValueList=new LinkedList<>();
                for (YlDevice device:ylDeviceList) {

                    //设备收益 没有订单 获取类别
                    YlDeviceCategory category=ylDeviceCategoryService.getById(device.getDeviceCategory());

                    //获取订单数据
                    List<Map<String, Object>> shopDeviceList=  ylPowerBankOrderService.getTwoShopDeviceOrder(stringList,m.get("id").toString(),device.getDeviceCategory(),type);
                    if (shopDeviceList.size()>0){
                        for (Map<String, Object> stringObjectMap: shopDeviceList) {
                            //设备收益
                            Map<String, Object> mapValue=new HashMap();
                            mapValue.put("categoryName",stringObjectMap.get("categoryName"));//设备类别名称
                            mapValue.put("mac",stringObjectMap.get("mac"));//MAC
                            mapValue.put("orderPrice",stringObjectMap.get("orderPrice"));//设备收益
                            mapValue.put("quantity",stringObjectMap.get("quantity"));//设备订单数
                            mapValue.put("incomeQuantity",stringObjectMap.get("orderPrice")+"/"+stringObjectMap.get("quantity"));// 单柜收益/订单
                            BigDecimal singlePrice= new BigDecimal(stringObjectMap.get("orderPrice").toString()).divide(new BigDecimal( category.getFullNumber()),2,BigDecimal.ROUND_HALF_UP);
                            BigDecimal orderQuantity= new BigDecimal(stringObjectMap.get("quantity").toString()).divide(new BigDecimal( category.getFullNumber()),2,BigDecimal.ROUND_HALF_UP);
                            mapValue.put("treasureQuantity",singlePrice+"/"+orderQuantity);//单宝收益/订单   单宝收益 （ 收益除以 仓口数）   订单数（订单数量 除以仓口数）
                            mapValueList.add(mapValue);
                        }
                    }else {

                        Map<String, Object> mapValue=new HashMap();
                        mapValue.put("categoryName",category.getCategoryName());//设备类别名称
                        mapValue.put("mac",device.getDeviceMac());//MAC
                        mapValue.put("orderPrice","0.0");//设备收益
                        mapValue.put("quantity","0");//设备订单数
                        mapValue.put("incomeQuantity","0/0");// 单柜收益/订单
                        mapValue.put("treasureQuantity","0/0");//单宝收益/订单
                        mapValueList.add(mapValue);

                    }

                }

                m.put("mapValueList",mapValueList);
                mapShopList.add(m);
            }

        }

        map.put("shopList",mapShopList);

//        存储缓存 redis 缓存数据 5分钟内有效
        redisUtil.set(key, map, 300);
        return Result.OK(map);
    }

    /**
     * APP运营端-撤机门店-2级页面
     * @param user 当前登陆用户
     * @param mark 标记 （1 、小组id 2、业务员id)
     * @param userId 业务id(标记传1传小组id、标记2 传业务员id   )
     * @param type 时间类型（2昨日、3本周、4本月）
     * @return
     */
    @Override
    public Result<?> getWeaningShopData(SysUser user, Integer mark, String userId, Integer type)throws ParseException {
        Date date= DateUtils.addDaysToDate(new Date(),-1);//取出昨天
        Map<String, Object> map=new HashMap();

        String key= "getWeaningShopData"+mark+userId+type;//缓存key
        Object object = redisUtil.get(key);
        if (object != null) {
            map=Map.class.cast(object);
            return Result.OK(map);
        }




        SimpleDateFormat formats = new SimpleDateFormat("yyyy-MM-dd");

        String zDays= formats.format(date);//昨天


        //获取更新时间
        map.put("payTime",zDays);
        String bdId=null;
        String groupId=user.getGroupIds();//用户所在小组
        if (mark==2){
            bdId=userId;
        }

        //取出 昨日 本周 本月
        List<YlWeaningShop>  weaningShopList=ylWeaningShopService.getWeaningShopAppList(bdId, groupId, type);
         //统计 撤机门店数 撤机KA门店数 撤机前7日均收益 撤机前30日均收益
        map.put("weaningShopQuantity",weaningShopList.stream().filter(s -> s.getKaShop() == 0).collect(Collectors.toList()).size());//撤机门店数
        map.put("kaShopQuantity",weaningShopList.stream().filter(s -> s.getKaShop() == 1).collect(Collectors.toList()).size());//KA撤机门店数
        map.put("sevenPrice","0.00");//撤机前7日均收益  计算规则 总收益 除以 7 再除以 店铺数量
        map.put("thirtyPrice","0.00");//撤机前30日均收益 计算规则 总收益 除以 30 再除以 店铺数量


        BigDecimal orderPrice=new BigDecimal("0.00");//收益金额

        BigDecimal thirtyPrice=new BigDecimal("0.00");//收益金额
       //组装 店铺数据
        List<Map<String, Object>> mapList=new ArrayList<>();
        for (YlWeaningShop weaningShop:weaningShopList) {
            Map<String, Object> shopMap=new HashMap<>();
            shopMap.put("shopName",weaningShop.getShopName());
            shopMap.put("kaShop",weaningShop.getKaShop());

            //根据 撤机时间 计算 7日所得收益  查询订单
            Date  unbindTime=   weaningShop.getUnbindTime();//设备解绑时间 就是结束时间
            //算出 范围时间
            Date sevenTime= DateUtils.addDaysToDate(unbindTime,-7);//取出 -7时间
            //开始时间
            String seven_monday=formats.format(sevenTime)+" 00:00:00";
            QueryWrapper<YlPowerBankOrder> queryWrapper= new QueryWrapper<YlPowerBankOrder>();
            queryWrapper.eq("group_id",groupId);
            if (oConvertUtils.isNotEmpty(bdId)){
                queryWrapper.eq("bd_id",bdId);
            }
            queryWrapper.between("create_time",seven_monday,unbindTime);
            queryWrapper.select("IFNULL(SUM(order_price),0) as orderPrice");

            Map<String, Object> objectMap= ylPowerBankOrderService.getMap(queryWrapper);
            orderPrice=orderPrice.add(new BigDecimal(objectMap.get("orderPrice").toString()));
            BigDecimal p=new BigDecimal(objectMap.get("orderPrice").toString());
            if (p.compareTo(new BigDecimal("0.00"))==0){//相等
                shopMap.put("sevenPrice","0.00");//七日 7日均收益是0
            }else {
                //坐计算 7天订单收益 除以 7日 得到均收益
                shopMap.put("sevenPrice",p.divide(new BigDecimal("7.00"),2,BigDecimal.ROUND_HALF_UP));//七日 7日均收益是0
            }
            Date thirtyTime= DateUtils.addDaysToDate(unbindTime,-30);//取出 -30天时间
            //开始时间
            QueryWrapper<YlPowerBankOrder> thirtyWrapper= new QueryWrapper<YlPowerBankOrder>();
            thirtyWrapper.eq("group_id",groupId);
            if (oConvertUtils.isNotEmpty(bdId)){
                thirtyWrapper.eq("bd_id",bdId);
            }
            thirtyWrapper.between("create_time",formats.format(thirtyTime)+" 00:00:00",unbindTime);
            thirtyWrapper.select("IFNULL(SUM(order_price),0) as orderPrice");
            Map<String, Object> thirtyMap= ylPowerBankOrderService.getMap(thirtyWrapper);
            thirtyPrice=thirtyPrice.add(new BigDecimal(thirtyMap.get("orderPrice").toString()));

            BigDecimal t=new BigDecimal(thirtyMap.get("orderPrice").toString());
            if (t.compareTo(new BigDecimal("0.00"))==0){//相等
                shopMap.put("thirtyPrice","0.00");//七日 30日均收益是0
            }else {
                //坐计算30天订单收益 除以 30日 得到均收益
                shopMap.put("thirtyPrice",t.divide(new BigDecimal("30.00"),2,BigDecimal.ROUND_HALF_UP));//七日 7日均收益是0
            }
            mapList.add(shopMap);
        }
        BigDecimal seven= orderPrice.divide(new BigDecimal("7.00"),2,BigDecimal.ROUND_HALF_UP);
        BigDecimal thirty= thirtyPrice.divide(new BigDecimal("30.00"),2,BigDecimal.ROUND_HALF_UP);
        if (mapList.size()>0){
            map.put("sevenPrice",seven.divide(new BigDecimal(mapList.size()),2,BigDecimal.ROUND_HALF_UP).toString());//撤机前7日均收益  计算规则 总收益 除以 7 再除以 店铺数量
            map.put("thirtyPrice",thirty.divide(new BigDecimal(mapList.size()),2,BigDecimal.ROUND_HALF_UP).toString());//撤机前30日均收益 计算规则 总收益 除以 30 再除以 店铺数量
        }
        //求出近三十天的折线图 每天撤机门店数
        Date thirtyDate= DateUtils.addDaysToDate(new Date(),-30);//取出前30的日期
        String thirtyDays= formats.format(thirtyDate);//昨天

        List<String> daysList= DateUtils.rangeDates(thirtyDays,zDays);//求出时间范围
        List<Map<String,Object>>  shopLineChartListMap=new ArrayList<>();


        List<Map<String,Object>>  shopLineChartList=ylWeaningShopRecordService.getUnbindShopLineChart(groupId, bdId, thirtyDays+" 00:00:00", zDays+" 23:59:59");
        for (String d : daysList) {
            Map dayMap=new HashMap();
            String[] s=  d.split("-");
            dayMap.put("tian",s[1]+"."+s[2]);

            List<Map<String,Object>>  ifMap=  shopLineChartList.stream().filter(m ->  m.get("type").toString() .equals(d) ).collect(Collectors.toList());
            if (ifMap.size()>0){
                dayMap.put("shopQuantity",ifMap.get(0).get("shopQuantity"));
            }else {
                dayMap.put("shopQuantity",0);
            }
            shopLineChartListMap.add(dayMap);
        }
        map.put("shopLineChartList",shopLineChartListMap);
        map.put("shopList",mapList);


        //        存储缓存 redis 缓存数据 5分钟内有效
        redisUtil.set(key, map, 600);

        return Result.OK(map);
    }

    /**
     * APP运营端-新增门店-2级页面
     * @param user 当前登陆用户
     * @param mark 标记 （1 、小组id 2、业务员id)
     * @param userId 业务id(标记传1传小组id、标记2 传业务员id   )
     * @param type 时间类型（1今日、2昨日、3本周、4本月）
     * @return
     */
    @Override
    public Result<?> getAddShopData(SysUser user, Integer mark, String userId, Integer type) {
        Map<String, Object> map=new HashMap();

        String key= "getAddShopData"+user.getId()+mark+userId+type;//缓存key
        Object object = redisUtil.get(key);
        if (object != null) {
            map=Map.class.cast(object);
            return Result.OK(map);
        }



        if (type==2){//昨日时间
            Date date= DateUtils.addDaysToDate(new Date(),-1);//取出昨天
            SimpleDateFormat formats = new SimpleDateFormat("yyyy-MM-dd");
            //获取更新时间
            map.put("payTime",formats.format(date));
        }else {
            SimpleDateFormat formats = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            //获取更新时间
            map.put("payTime",formats.format(new Date()));
        }

        String sId=null;//组员id
        String groupId=null;//组长id
        //根据 type 获取相应的店铺
        List<Map> ylShopList=new ArrayList<>();
        if (mark==1){//小组id
            ylShopList= ylShopService.getAddShopList(type, null, userId);
            groupId=userId;
        }else {
            ylShopList= ylShopService.getAddShopList(type, userId, null);
            sId=userId;
        }

        if (ylShopList.size()==0){
            //新铺门店
            map.put("shopQuantity",0);//店铺数量
            map.put("orderQuantity",0);//订单数量
            map.put("incomePrice",0);//累计收益
            map.put("powerPrice",0);//单宝收益
            map.put("ylShopList",new ArrayList<>());
        }else {
            map.put("shopQuantity",ylShopList.size());//店铺数量
            Integer orderQuantity=0;//模拟订单 总数
            BigDecimal incomePrice=new BigDecimal("0.00");//累计收益
            BigDecimal powerPrice=new BigDecimal("0.00");//单宝收益
            for (Map  shopMap:ylShopList){
                Map<String, Object>  stringObjectMap=   ylPowerBankOrderService.getMap(new QueryWrapper<YlPowerBankOrder>().eq("lease_shop_id",shopMap.get("id").toString()).select("count(id)AS quantity,IFNULL(SUM(order_price), 0)AS orderPrice,IFNULL(SUM(single_price), 0)AS singlePrice"));
                orderQuantity=orderQuantity+Integer.parseInt(stringObjectMap.get("quantity").toString());
                incomePrice=incomePrice.add(new BigDecimal(stringObjectMap.get("orderPrice").toString()));

                Map<String, Object> deviceQuantity=  ylDeviceService.getShopIdDeviceQuantity(shopMap.get("id").toString());
                Integer fullNumber= Integer.parseInt(deviceQuantity.get("fullNumber").toString());//仓孔数

                if (0==fullNumber){
                    shopMap.put("powerPrice","0.00");
                }else {
                    BigDecimal singlePrice= new BigDecimal(stringObjectMap.get("orderPrice").toString()).divide(new BigDecimal(fullNumber),2,BigDecimal.ROUND_HALF_UP);
                    powerPrice=powerPrice.add(singlePrice);
                    shopMap.put("powerPrice",singlePrice.toString());
                }
                shopMap.put("incomePrice",stringObjectMap.get("orderPrice").toString());

            }
            map.put("orderQuantity",orderQuantity);//订单数量
            map.put("incomePrice",incomePrice);//累计收益
            map.put("powerPrice",powerPrice);//单宝收益
            map.put("ylShopList",ylShopList);
        }

        //求出折线图
        map.put("shopList", ylShopService.getHomeShopLineChart(30, sId, groupId));
        redisUtil.set(key, map, 300);
        return Result.OK(map);
    }

    /**
     * APP运营端-首页门店统计(折线图默认7天)
     * @param user 请求用户
     * @return
     */
    @Override
    public Result<?> getHomeShopQuantity(SysUser user) {
        SimpleDateFormat formats = new SimpleDateFormat("MM.dd HH:mm");
        Map<String, Object> map=new HashMap();



        String key= "getHomeShopQuantity"+user.getId();//缓存key
        Object object = redisUtil.get(key);
        if (object != null) {
            map=Map.class.cast(object);
            return Result.OK(map);
        }






        //获取更新时间
        map.put("payTime",formats.format(new Date()));
        String sId=null;//组员id
        String groupId=null;//组长id
        Integer identity=0;//模拟身份 是否组长1是2否
        //判断是不是组长 是否组长1是2否
        if (user.getIsLeaders().equals("1")){
            groupId=user.getGroupIds();
            identity=1;
        }else {
            //根据群组id 获取数据id
            sId=user.getId();
            identity=2;
        }
        //取出 1柜机门店数 2、0收益门店数、3 新铺门店数 4 撤机门店数 5净增门店数
        List<Map>mapList=new LinkedList<>();
        Map<String, Object> map1=new HashMap();
        map1.put("type",1);
        map1.put("quantity", ylHomeShopService.getHomeShopQuantity(sId, groupId, 1, 0));
        mapList.add(map1);
        Map map2=new HashMap();
        map2.put("type",2);
        map2.put("quantity",  ylHomeShopService.getHomeShopQuantity(sId, groupId, 2, 0));
        mapList.add(map2);
        //新增店铺 近7天
        Map map3=new HashMap();
        map3.put("type",3);
        map3.put("quantity",  ylShopService.getHomeShopStatistics(7, sId, groupId));
        mapList.add(map3);
        Map map4=new HashMap();
        map4.put("type",4);
        map4.put("quantity",  ylHomeShopService.getHomeShopQuantity(sId, groupId, 4, 0));
        mapList.add(map4);

        //// 1 本月店铺数据  2、上个月店铺数据    指(本月截止至昨日最后时刻的总门店数)-(上月最后时刻的总门店数)的差值

        Integer z= ylHomeShopService.getHomeShopQuantity(sId, groupId, 5, 2);//上个月店铺数据
        Integer j= ylHomeShopService.getHomeShopQuantity(sId, groupId, 5, 1);//本月

        Map map5=new HashMap();
        map5.put("type",5);
        map5.put("quantity",  j-z);
        mapList.add(map5);
        map.put("shopStatisticsList",mapList);

        //求出折线图
        map.put("shopList", ylShopService.getHomeShopLineChart(7, sId, groupId));

//        存储缓存 redis 缓存数据 5分钟内有效
        redisUtil.set(key, map, 300);

        return Result.OK(map);
    }

    /**
     * APP运营端-首页租借订单统计数量(折线图默认7天)
     * @param user 请求用户
     * @return
     */
    @Override
    public Result<?> getAppPowerBankOrderQuantity(SysUser user) {
        SimpleDateFormat formats = new SimpleDateFormat("MM.dd HH:mm");
        String dateStr= formats.format(new Date());//当前请求时间
        Map map=new HashMap();
        String key= "getAppPowerBankOrderQuantity"+user.getId();//缓存key
        Object object = redisUtil.get(key);
        if (object != null) {
            map=Map.class.cast(object);
            return Result.OK(map);
        }
        //获取更新时间
        map.put("payTime",dateStr);


        String sId=null;

        String groupId=null;
        List<String> stringList=new LinkedList<>();
        //判断是不是组长 是否组长1是2否
        if (user.getIsLeaders().equals("1")){
            stringList=ylGroupService.getGroupUserById(user.getGroupIds());
            groupId=user.getGroupIds();
        }else {
            //根据群组id 获取数据id
            stringList.add(user.getId());
            sId=user.getId();
        }
        List<Map>mapList=new LinkedList<>();
        //求出今日下单数
        Map<String, Object>  dayPowerBankOrder= ylPowerBankOrderService.getHomePowerBankOrder(stringList,1);//今日
        Map map1=new HashMap();
        map1.put("type",1);
        map1.put("quantity",dayPowerBankOrder.get("quantity"));
        mapList.add(map1);
        //求出今日归还数量
        Map map2=new HashMap();
        map2.put("type",2);
        map2.put("quantity", ylPowerBankOrderService.getHomePowerBankOrderQuantity(stringList,1).get("quantity"));
        mapList.add(map2);
        //求出本月归还数量
        Map map3=new HashMap();
        map3.put("type",3);
        map3.put("quantity", ylPowerBankOrderService.getHomePowerBankOrderQuantity(stringList,4).get("quantity"));
        mapList.add(map3);


        //求出 硬件错误订单数
        Map map4=new HashMap();
        map4.put("type",4);
        map4.put("quantity", ylProblemOrderService.getProblemOrderQuantity(sId,groupId,3,null,null));
        mapList.add(map4);




        map.put("powerBankOrderChartList",mapList);


        List<Map>appPowerBankOrderOrderDayList=new LinkedList<>();

         //求出折线图数据 查询近7天的数据
        List<String> daysList= DateUtils.getThisYearMonthDays(7);//求出时间范围
        for (String date : daysList) {
//            System.out.println(date);
            Map dayMap=new HashMap();
            String[] s=  date.split("-");
            dayMap.put("tian",s[1]+"."+s[2]);
            Map<String, Object> d=  ylPowerBankOrderService.getDayOrderQuantity(stringList,date,1);//今日 1 今日下单  2归还充电宝
            Map<String, Object> g=  ylPowerBankOrderService.getDayOrderQuantity(stringList,date,2);//今日 1 今日下单  2归还充电宝
            dayMap.put("quantity",d.get("quantity"));//当天下单还数
            dayMap.put("returnQuantity",g.get("quantity"));//当天归还数
            appPowerBankOrderOrderDayList.add(dayMap);
        }
        map.put("appPowerBankOrderOrderDayList",appPowerBankOrderOrderDayList);
        //存储缓存 redis 缓存数据 5分钟内有效
        redisUtil.set(key, map, 300);
        return Result.OK(map);

    }

    /**
     * 首页租借收益订单折线图
     * @param user 当前登陆数据
     * @param cycleTime 1 、30天 2、 6个月
     * @return
     */
    @Override
    public Result<?> getIncomeLineChart(SysUser user, Integer cycleTime) {
        SimpleDateFormat formats = new SimpleDateFormat("MM.dd HH:mm");
        String dateStr= formats.format(new Date());//当前请求时间
        List<String> stringList=new LinkedList<>();
        Map map=new HashMap();
        String key= "getIncomeLineChart"+user.getId()+cycleTime;//缓存key
        Object object = redisUtil.get(key);
        if (object != null) {
            map=Map.class.cast(object);
            return Result.OK(map);
        }

        List<Map>mapList=new LinkedList<>();
        //判断是不是组长 是否组长1是2否
        if (user.getIsLeaders().equals("1")){
            stringList=ylGroupService.getGroupUserById(user.getGroupIds());
        }else {
            //根据群组id 获取数据id
            stringList.add(user.getId());
        }

        Map<String, Object>  dayPowerBankOrder= ylPowerBankOrderService.getAppPowerBankOrderIncome(stringList,1);//今日
        Map map1=new HashMap();
        //获取更新时间
        map.put("payTime",dateStr);


        map1.put("type",1);
        map1.put("orderPrice",dayPowerBankOrder.get("orderPrice"));
        mapList.add(map1);
        Map map2=new HashMap();
        map2.put("type",2);
        map2.put("orderPrice",ylPowerBankOrderService.getAppPowerBankOrderIncome(stringList,2).get("orderPrice"));//昨日
        mapList.add(map2);
        Map map3=new HashMap();
        map3.put("type",4);
        map3.put("orderPrice",ylPowerBankOrderService.getAppPowerBankOrderIncome(stringList,4).get("orderPrice"));//本月、
        mapList.add(map3);
        map.put("powerBankOrderChartList",mapList);

        //折线图
        if (cycleTime==1){
            //获取近30天的日期区间
            Calendar calendar =   new  GregorianCalendar();
            calendar.set(Calendar.HOUR_OF_DAY,0);
            calendar.set(Calendar.MINUTE,0);
            calendar.set(Calendar.SECOND,0);
            calendar.set(Calendar.MILLISECOND,0);
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            Date dayEnd = calendar.getTime();
            calendar.add(Calendar.DAY_OF_MONTH, -30);
            Date dayStart = calendar.getTime();
            map.put("appPowerBankOrderOrderDayList",ylPowerBankOrderService.getPowerBankOrderOrderDayList(stringList,dayStart, dayEnd));
        }else {
            //六个月
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY,0);
            calendar.set(Calendar.MINUTE,0);
            calendar.set(Calendar.SECOND,0);
            calendar.set(Calendar.MILLISECOND,0);
            calendar.set(Calendar.DAY_OF_MONTH,1);
            calendar.add(Calendar.MONTH, -6);
            Date dayStartYue = calendar.getTime();//开始时间
            map.put("appPowerBankOrderOrderDayList",ylPowerBankOrderService.getPowerBankOrderOrderYueList(stringList,dayStartYue, new Date()));
        }
        //存储缓存 redis 缓存数据 5分钟内有效
        redisUtil.set(key, map, 300);
        return Result.OK(map);
    }
}
